package com.gecba.modular.shiro.filter;

import com.gecba.modular.shiro.JwtToken;
import com.gecba.modular.shiro.constant.Constants;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ChenBo
 * @className JwtFilter
 * @date 2021/9/5
 */
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class JwtFilter extends BasicHttpAuthenticationFilter {

    private boolean allowOrigin=true;


    /**
     *执行登录认证
     *@author ChenBo
     *@date 2021/9/5
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
      try {
        return executeLogin(request, response);
      }catch (Exception e){
          throw new AuthenticationException("Token失效，请重新登录", e);
      }
    }

    /**
     *获取请求token
     *@author ChenBo
     *@date 2021/9/5
     */
    @Override
    protected boolean executeLogin(ServletRequest servletRequest, ServletResponse response) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(Constants.X_ACCESS_TOKEN);
        if(StringUtils.isBlank(token)){
            token = request.getParameter(Constants.TOKEN);
        }

        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(servletRequest,response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    /**
     *对跨域提供支持
     *@author ChenBo
     *@date 2021/9/5
     */
    @Override
    protected boolean preHandle(ServletRequest servletRequest, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if(allowOrigin){
            httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
            //update-begin-author:scott date:20200907 for:issues/I1TAAP 前后端分离，shiro过滤器配置引起的跨域问题
            // 是否允许发送Cookie，默认Cookie不包括在CORS请求之中。设为true时，表示服务器允许Cookie包含在请求中。
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            //update-end-author:scott date:20200907 for:issues/I1TAAP 前后端分离，shiro过滤器配置引起的跨域问题
        }
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(servletRequest, response);
    }
}
